package org.tsinghua.answer.domain.security;

import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.List;

import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.tsinghua.answer.domain.user.User;

public class MyUserDetails implements UserDetails {

	private static final long serialVersionUID = 3394764981925758141L;
	
	private User user;
	
	public User getUser() {
		return user;
	}
	
	public MyUserDetails(User user) {
		this.user = user;
		if(user.isEnabled()) {
			String role = user.getType().toString();
			SimpleGrantedAuthority authority = new SimpleGrantedAuthority(role);
			authorities = Arrays.asList(authority);
		}
		
	}
	
	private List<? extends GrantedAuthority> authorities = Collections.emptyList();
	
	@Override
	public Collection<? extends GrantedAuthority> getAuthorities() {
		return authorities;
	}

	@Override
	public String getPassword() {
		return user.getPassword();
	}

	@Override
	public String getUsername() {
		return user.getUsername();
	}

	@Override
	public boolean isAccountNonExpired() {
		return true;
	}

	@Override
	public boolean isAccountNonLocked() {
		return !user.isLocked();
	}

	@Override
	public boolean isCredentialsNonExpired() {
		return true;
	}

	@Override
	public boolean isEnabled() {
		return user.isEnabled();
	}

}
